import 'dart:async';

import 'package:device_uuid/device_uuid.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';

import '../http/api/api.dart';
import '../http/api/login.dart';
import '../model/ai/ai_models.dart';
import '../model/classify/classify_models.dart';
import '../model/deduct/deduct_models.dart';
import '../utils/enum.dart';
import '../utils/logger.dart';
import '../utils/m3u8_download/local_server.dart';
import '../utils/m3u8_download/m3u8_downloader_manager.dart';
import '../utils/uuid.dart';
import 'storage_service.dart';
import 'user_service.dart';

class AppService extends GetxService {
  // 暂时没有提供obs, 手动update, 有需要再改
  List<ClassifyModel> shiPinTabs = <ClassifyModel>[];
  bool hasForbidden = false;
  // 暂时没有提供obs, 手动update, 有需要再改
  AiEntranceConfigModel aiEntrance = AiEntranceConfigModel.empty();
  DeductTypeModel? deducts;

  String? androidLandURL;
  // <error>
  Completer<Object?> networkInitCompleter = Completer();

  // 短视频页面是否展示广告，全局生效，直至重启
  final _shortShowAd = true.obs;

  void hideShortAd() => _shortShowAd.value = false;
  bool get shortShowAd => !Get.find<UserService>().isVIP && _shortShowAd.value;

  Future<AppService> init() async {
    await _initDeviceId();

    _sendNetworkInitReq();
    if (!kIsWeb) {
      M3u8DownloadManager.loadRecords();
      LocalServer.setup();
    }
    return this;
  }

  Future<Object?> _sendNetworkInitReq() {
    Future.wait([
      _updateClassifyTabs(),
      updateDeducts(),
      updateAiEntrance(),
      getSharedLink(),
    ]).then((_) {
      // if (shiPinTabs.isEmpty) {
      //   networkInitCompleter.complete('首页初始化失败');
      // } else {
      //   networkInitCompleter.complete(null);
      // }
    }).onError((err, stack) {
      networkInitCompleter.complete(err ?? '初始化失败');
    });
    return networkInitCompleter.future;
  }

  Future<bool> _updateClassifyTabs() async {
    final shiPinClassify = await Api.fetchShiPinClasifyList();
    if (shiPinClassify != null) {
      hasForbidden = shiPinClassify.firstWhereOrNull(
              (e) => e.type == ShiPinClassifyTypeEnum.forbidden) !=
          null;
      shiPinTabs.assignAll(shiPinClassify);
    }
    return true;
  }

  Future updateDeducts() async {
    final resp = await Api.fetchDeductType();
    if (resp?.status == true) {
      deducts = resp;
    }
  }

  ///作为安卓更新用的
  Future getSharedLink() async {
    try {
      final result = await Api.getShareLink();
      androidLandURL = result?.url ?? '';
    } catch (e) {
      logger.d('$e');
    }
  }

  Future<bool> updateAiEntrance() async {
    final resp = await Api.fetchAiEntranceConfig();
    if (resp == null) return false;
    aiEntrance = resp;
    return true;
  }

  Future<void> _initDeviceId() async {
    /// 从Get中查找注册过的 StorageService 工具类实例
    final storageService = Get.find<StorageService>();

    /// 查找设备ID
    /// 如果没有,则进行生成
    if (storageService.deviceId == null) {
      String deviceId;
      if (GetPlatform.isWeb) {
        deviceId = UUID.generate();
      } else {
        deviceId = (await DeviceUuid().getUUID() ?? '').trim();
      }

      /// 存储新创建的UUID(设备ID)
      await storageService.setDeviceId(deviceId);
      await login(deviceId);
    } else {
      await login(storageService.deviceId!);
    }
    logger.d('deviceId: ${storageService.deviceId}');
  }
}
